import React, { Fragment } from 'react'
import './index.less'
import Tabs from '../../components/Tabs';
import http from 'libs/http'
import { Icon, Upload } from 'antd'
import { getWeek, s_alert, _alert, downloadByObjectKey } from 'libs/utils'
import { MediaPlayer, NoData, Dialog } from 'components'

export default class extends React.Component {
  state = {
    tabsData: [
      { courseType: 0, name: '全部课程', active: true },
      { courseType: 1, name: '龙英语', },
      { courseType: 3, name: '龙编程' },
      { courseType: 2, name: '龙数学' },
    ],
    courseType: 0,
    liveCourses: [],
    mediaSrc: '',
    mediaTitle: '',
    mediaShow: false,
    loading: [],
  }

  componentDidMount() {
    this.getCourseTables()
  }

  // 获取直播课列表
  getCourseTables = () => {
    const { courseType } = this.state
    http.get('/student/course-table/list', { courseType }).then(res => {
      const liveCourses = res.data
      this.setState({ liveCourses })
    })
  }

  // 全部课程、龙英语、龙编程之间切换
  changeTab = index => () => {
    const { tabsData } = this.state
    let courseType = 0
    tabsData.map((tab, i) => {
      if(index === i) {
        tab.active = true
        courseType = tab.courseType
      }else{
        tab.active = false
      }
    })
    this.setState({
      tabsData, courseType
    }, this.getCourseTables)
  }

  // 点击上课
  handleGoClass = (classStartStatus, tableId) => () => {
    if(!classStartStatus) return
    const showErrorNotice = true
    http.post('/student/business/classBegin', { tableId }, undefined, showErrorNotice).then(res => {
      const data = res.data || {}
      const { platform, url, tvUrl, courseName, token='' } = data
      if(platform === 1){
        const url = 'http://www.zilongshu.com/baijiayun/index.html?token='+token
        // s_alert('是否进入课堂？', url)
        Dialog({
          message: '是否进入课堂？',
          cancelBtn: '取消',
          okCallback: () => {
            window.open(url)
          }
        })
      }
      else if(platform === 2){
        // s_alert('是否进入课堂？', url)
        Dialog({
          message: '是否进入课堂？',
          cancelBtn: '取消',
          okCallback: () => {
            window.open(url)
          }
        })
      }
      else if(platform === 3){
        this.setState({ videoUrl: tvUrl, showVideo: true, videoTitle: courseName })
      }
    })
  }

  // 原声诵读，素材下载
  lookMaterial = (type, tableId, courseName) => () => {
    http.get('/student/business/lookMaterial', { tableId, type }).then(res => {
      console.log('%c 预习资料/课程资料，原声诵读，素材下载', 'color: red;', type, res)
      // 预习资料/课程资料，打开新页面
      if(type === 1) {
        
      }
      // 原声诵读，返回的是mp4，打开视频播放器
      else if(type === 2) {
        this.setState({
          mediaShow: true,
          mediaTitle: courseName,
          mediaSrc: res.data
        })
      }
      // 素材下载，oss方式，配置文件在config.js中，下载实现在utils.js中
      else if(type === 3) {
        downloadByObjectKey(res.data)
      }
    })
  }

  // /课程资料
  lookMaterial2 = (type, tableId) => () => {
    
    http.get('/student/course-table/getMaterId', { tableId, type }).then(res => {
      this.props.history.push(`/student_center_/material/${res.data}/${type}`)
    })
    
  }
  
  // 任务上传 
  uploadCourseTask = index => info => {
    const loading = this.state.loading;
    if (info.file.status === 'uploading') {
      loading[index] = true;
      this.setState({ loading });
      return;
    }
    if (info.file.status === 'done') {
      loading[index] = false;
      // _alert('作业已上传成功!');
      Dialog({
        message: '作业已上传成功！'
      })
      this.setState({ loading });
    }
    if (info.file.status === 'error') {
      loading[index] = false;
      this.setState({ loading });
      // _alert('上传失败，请重新上传!');
      Dialog({
        message: '上传失败，请重新上传!'
      })
    }
  }

  onCancelMediaPlayer = () => {
    this.setState({ mediaShow: false, mediaSrc: '', mediaTitle: '' })
  }

  openHomework = (tableId) => () => {
    const showErrorNotice = true
    const winRef = window.open("", "_blank")
    http.post('/student/business/createExam', { tableId }, undefined, showErrorNotice).then(res => {
      const { examId } = res.data
        if (examId) {
          setTimeout(() => {
            winRef.location = '/#/student_center_/my_courses/layout/homework?examId='+examId
          }, 800);
          // this.props.history.push(`/student/wodekecheng/zaixianshiti/${examId}`);
          // window.open('/#/student_center_/my_courses/layout/homework?examId='+examId)
        } else {
          // _alert('题库尚未维护成功,请联系对应的课程顾问!');
          Dialog({
            message: '题库尚未维护成功,请联系对应的课程顾问!'
          })
        }
    })
  }
  // 在线编程
  handleGoScratch3 = () => {
    const scratchRef = window.open("", "_blank")
    setTimeout(() => {
      scratchRef.location = `http://scratch.zilongshu.com/`;
    }, 800);
  }
  // 预习资料
  // prepareMaterial = (type, tableId) => () => {
  //   http.get('/student/course-table/getMaterId', { tableId, type }).then(res => {
  //     window.open(`/#/student_center_/material/${res.data}/${type}`)
  //   })
  // }
  prepareMaterial = (type, tableId) => () => {
    const showErrorNotice = true
    const winRef = window.open("", "_blank")
    http.get('/student/course-table/getMaterId', { tableId, type }).then(res => {
      // window.open(`/#/student_center_/material/${res.data}/${type}`)
      if(res.code == 1){
        setTimeout(() => {
          winRef.location = `/#/student_center_/material/${res.data}/${type}`
        }, 800);
      }else{
        Dialog({
          message: '题库尚未维护成功,请联系对应的课程顾问!'
        })
      }
    })
  }
  render() {
    const { tabsData, liveCourses, mediaSrc, mediaShow, mediaTitle, loading } = this.state
    return (
      <div className="live-course-list">
        <Tabs tabsData={tabsData} changeTab={this.changeTab} fontColor="#fff" />
        <div className="live-course-list-content">
          {
            liveCourses.length > 0 ? (
              <ul>
                {
                  liveCourses.map((course, index) => {
                    const { 
                      tableId, classBeginTime, classNameStatus, classStartStatus, 
                      courseName, lesson, level, teacherName, teacherPictureUrl,
                      courseType,
                    } = course
                    return (
                      <li key={tableId}>
                        <div className="live-left">
                          <p>
                            <span>{classBeginTime.substr(0, 10)}</span>
                            <span>{getWeek(classBeginTime, '周')} {classBeginTime.substr(11, 5)}</span>
                          </p>
                          <span className="circle"></span>
                        </div>
                        <div className="live-right">
                          <div className="course-name">
                            <b>{courseName}</b>
                            <span><img src={teacherPictureUrl} />{teacherName}</span>
                          </div>
                          <div className="course-level">
                            <span>课程等级:<b>{level}</b></span>
                            <span>学习进度:<b>{lesson}</b></span>
                          </div>
                          <div className="course-action">
                            {
                              courseType === 1 && (
                                <Fragment>
                                  <span className="span" onClick={this.prepareMaterial(1, tableId)}><Icon type="play-circle" /><b>预习资料</b></span>
                                  <span className="span" onClick={this.lookMaterial(2, tableId, courseName)}><Icon type="play-circle" /><b>原声诵读</b></span>
                                  <span className="span" onClick={this.openHomework(tableId)}><Icon type="edit" /><b>课后练习</b></span>
                                  <Upload
                                    name="file"
                                    style={{width: 120, marginLeft: 6}}
                                    action={`/student/business/uploadCourseTask?tableId=${tableId}`}
                                    showUploadList={false}
                                    onChange={this.uploadCourseTask(index)}
                                  >
                                    <Icon type={loading[index] ? 'loading' : 'upload'} /><span className="span">任务上传</span>
                                  </Upload>
                                </Fragment>
                              ) 
                              // || (
                              //   <Fragment>
                              //     <span className="span" onClick={this.lookMaterial2(1, tableId)}><Icon type="play-circle" /><b>课程资料</b></span>
                              //     <span className="span" onClick={this.lookMaterial(3, tableId)}><Icon type="download" /><b>素材下载</b></span>
                              //     <span className="span" onClick={this.handleGoScratch3}><Icon type="desktop" /><b>在线编程</b></span>
                              //     <Upload
                              //       name="file"
                              //       style={{width: 120, marginLeft: 6}}
                              //       action={`/student/business/uploadCourseTask?tableId=${tableId}`}
                              //       showUploadList={false}
                              //       onChange={this.uploadCourseTask(index)}
                              //     >
                              //       <Icon type={loading[index] ? 'loading' : 'upload'} /><span className="span">任务上传</span>
                              //     </Upload>
                              //   </Fragment>
                              // )
                            }
                            {
                              courseType === 2 && <Fragment>
                                <span className="span" onClick={this.lookMaterial2(1, tableId)}><Icon type="play-circle" /><b>课程教材</b></span>
                                <span className="span" onClick={this.openHomework(tableId)}><Icon type="edit" /><b>课后练习</b></span>
                                <Upload
                                  name="file"
                                  style={{width: 120, marginLeft: 6}}
                                  action={`/student/business/uploadCourseTask?tableId=${tableId}`}
                                  showUploadList={false}
                                  onChange={this.uploadCourseTask(index)}
                                >
                                  <Icon type={loading[index] ? 'loading' : 'upload'} /><span className="span">任务上传</span>
                                </Upload>
                              </Fragment>
                            }
                            {
                              courseType === 3 && <Fragment>
                              <span className="span" onClick={this.lookMaterial2(1, tableId)}><Icon type="play-circle" /><b>课程资料</b></span>
                              <span className="span" onClick={this.lookMaterial(3, tableId)}><Icon type="download" /><b>素材下载</b></span>
                              <span className="span" onClick={this.handleGoScratch3}><Icon type="desktop" /><b>在线编程</b></span>
                              <Upload
                                name="file"
                                style={{width: 120, marginLeft: 6}}
                                action={`/student/business/uploadCourseTask?tableId=${tableId}`}
                                showUploadList={false}
                                onChange={this.uploadCourseTask(index)}
                              >
                                <Icon type={loading[index] ? 'loading' : 'upload'} /><span className="span">任务上传</span>
                              </Upload>
                            </Fragment>
                            }
                          </div>
                          <div className="course-btn">
                            <span 
                              className={classStartStatus ? 'enable' : 'disable'} 
                              onClick={this.handleGoClass(classStartStatus, tableId)}
                            >{classNameStatus ? '上课' : '结束'}</span>
                            <i className={courseType === 1 ? 'english-icon' : (courseType === 3 ? 'program-icon' : 'math-icon')}>
                              {courseType === 1 ? '英语' : (courseType === 3 ? '编程' : '')}
                            </i>
                          </div>
                        </div>
                      </li>
                    )
                  })
                }
              </ul>
            ) : <NoData />
          }
        </div>
        <MediaPlayer
          src={mediaSrc}
          title={mediaTitle}
          show={mediaShow}
          onCancel={this.onCancelMediaPlayer}
        />
      </div>
    )
  }
}